
package com.yimixian.app.user;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.ta.utdid2.android.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.OrderListPointTab;
import com.yimixian.app.EventBusDomain.ShowAdSelectChange;
import com.yimixian.app.R;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.Address;
import com.yimixian.app.model.AppConfig;
import com.yimixian.app.rest.api.QuitLoginAPI;
import com.yimixian.app.ui.BaseHttpFragment;
import com.yimixian.app.ui.MessageDialogView;
import com.yimixian.app.util.CacheUtils;
import com.yimixian.app.util.SharedPreferencesHelper;

import org.json.JSONObject;

import java.io.File;

import butterknife.ButterKnife;
import butterknife.InjectView;
import de.greenrobot.event.EventBus;

/**
 * Created by zhilian-2 on 2015/10/17.
 */
public class SettingFragment extends BaseHttpFragment {

    @InjectView(R.id.quit_button)
    TextView mQuitButton;
    @InjectView(R.id.version_code_text)
    TextView mVersionCodeTextView;
    @InjectView(R.id.clear_cache_button)
    TextView mClearCacheButton;
    @InjectView(R.id.cache_size)
    TextView mCacheSizeText;
    @InjectView(R.id.fl_dialog_container)
    FrameLayout mDialogView;

    DataManager mDataManager;
    QuitLoginAPI mQuitLoginAPI;
    private Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_setting, null);
        ButterKnife.inject(this, view);
        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mDataManager = DataManager.getInstance();

        String versionName = mDataManager.get(CacheKeys.VERSION_NAME);
        Integer versionCode = mDataManager.get(CacheKeys.VERSION_CODE);
        mVersionCodeTextView.setText("版本号：" + versionName + "(" + versionCode + ")");
        mQuitButton.setVisibility(isLogin() ? View.VISIBLE : View.GONE);
        mQuitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchData(true, null);
            }
        });
        setCacheSizeTextData();
        mClearCacheButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isAdded()) {
                    File file = new File("/data/data/com.yimixian.app/cache/picasso-cache");
                    CacheUtils.clearCache(file, getActivity());
                }
            }
        });
        return view;
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    /** 判断是否登录 */
    public boolean isLogin() {
        if (DataManager.getInstance().get(CacheKeys.TOKEN) == null) {
            return false;
        }
        return true;
    }

    @Override
    public void initRequestAPI(String requestKeys) {
        String token = DataManager.getInstance().get(CacheKeys.TOKEN);
        if (StringUtils.isEmpty(token)) return;
        mQuitLoginAPI = new QuitLoginAPI(token, this);
    }

    @Override
    public void onHttpSuccess(String url, JSONObject responseJson) {
        hideDialog();
        MobclickAgent.onEvent(getActivity(), StatConstants.SETTING_QUIT_CLICK);
        mDataManager.remove(CacheKeys.TOKEN);
        SharedPreferencesHelper.clearUser(SharePreferenceKeys.CURRENT_USER);
        CartManager.getInstance().clearCart();
        CartManager.getInstance().clearOfflineData();
        SharedPreferencesHelper.clearAddress(SharePreferenceKeys.ADDRESSES);
//        SharedPreferencesHelper.clearAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        EventBus.getDefault().postSticky(new String(Constants.CART_TOTAL_PRICE_CHANGE_BROADCAST));
        mDataManager.remove(CacheKeys.CURRENT_USER);
        mDataManager.remove(CacheKeys.ORDERS);
        if (isAdded()){
            //清除小红点（）
            EventBus.getDefault().postSticky(new OrderListPointTab(0, Constants.RedPointType.BOUNS, false));
            getActivity().setResult(getActivity().RESULT_OK);
            EventBus.getDefault().postSticky(new ShowAdSelectChange());
            getActivity().finish();
        }
        Address curAddress = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if(curAddress == null){
            curAddress = new Address();
            curAddress.id = -1;
        }
        SharedPreferencesHelper.saveAddress(curAddress, SharePreferenceKeys.CURRENT_NO_LOGIN_ADDRESS);
    }

    @Override
    public void OnHttpFailure(String url, String errorMessage,boolean errorFromUs) {
        hideDialog();
    }

    @Override
    public void fetchDataFromNetwork(String key) {
        initRequestAPI(key);
        if (mQuitLoginAPI == null) return;
        showDialog(null,false);
        mQuitLoginAPI.toQuitLogin();
    }

    public void onEventMainThread(String message) {
        if(message != null && "clear_finish".equals(message)) {
            if(isAdded() && mCacheSizeText != null) {
                setCacheSizeTextData();
            }
        }
    }

    private void setCacheSizeTextData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        File file = new File("/data/data/com.yimixian.app/cache/picasso-cache/");
                        mCacheSizeText.setText(android.text.format.Formatter.formatFileSize(getActivity(),
                            CacheUtils.getFileSizes(file)));
                    }
                });
            }
        }).start();
    }
}
